﻿using ciji.Application.Dto;
using ciji.Core;
using Furion.DatabaseAccessor;
using Microsoft.Data.SqlClient;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;

namespace ciji.Application.Data
{
    /// <summary>
    /// 机构登记评定
    /// </summary>
    [ApiDescriptionSettings("机构登记评定", Order = 700, Description = "机构登记评定")]
    [LoggingMonitor]
    public class OrgService : IDynamicApiController
    {
        private SqlSugarRepository<cts_OrganizationAssessType> _assessTypeRep;
        private SqlSugarRepository<cts_OrganizationGroup> _groupRep;
        private SqlSugarRepository<cts_AssessOrganization> _orgRep;
        private SqlSugarRepository<cts_OrganizationAssessInfo> _assessInfoRep;
        private SqlSugarRepository<cts_OrgAssessBedInfo> _bedInfoRep;
        private SqlSugarRepository<cts_OrgAssessServiceInfo> _serviceInfoRep;
        private SqlSugarRepository<cts_OrgAssessServiceBasicInfo> _basicInfoRep;
        private SqlSugarRepository<cts_OrgAssessSafeInfo> _safeInfoRep;
        private SqlSugarRepository<cts_OrganizationAssessResult> _resultRep;
        private SqlSugarRepository<cts_OrganizationImg> _orgImgRep;
        private SqlSugarRepository<cts_AssessOrgImg> _assessOrgImgRep;
        private SqlSugarRepository<cts_OrgAssessBedType> _bedTypeRep;
        private SqlSugarRepository<cts_OrgAssessBedImg> _bedImgRep;
        private SqlSugarRepository<cts_OrgAssessServiceType> _serviceTypeRep;
        private SqlSugarRepository<cts_OrgAssessServiceImg> _serviceImgRep;
        private SqlSugarRepository<cts_OrgAssessServiceBasicType> _basicTypeRep; 
        private SqlSugarRepository<cts_OrgAssessServiceBasicImg> _basicImgRep;

        private SqlSugarRepository<cts_OrgAssessSafeType> _safeTypeRep;
        private SqlSugarRepository<cts_OrgAssessSafeImg> _safeImgRep;
        





        private SqlSugarRepository<cts_Employee> _employeeRep;




        public OrgService(SqlSugarRepository<cts_OrganizationAssessType> assessTypeRep
            , SqlSugarRepository<cts_OrganizationGroup> groupRep
            , SqlSugarRepository<cts_AssessOrganization> orgRep
            , SqlSugarRepository<cts_OrganizationAssessInfo> assessInfoRep
            , SqlSugarRepository<cts_OrgAssessBedInfo> bedInfoRep
            , SqlSugarRepository<cts_OrgAssessServiceInfo> serviceInfoRep
            , SqlSugarRepository<cts_OrgAssessServiceBasicInfo> basicInfoRep
            , SqlSugarRepository<cts_OrgAssessSafeInfo> safeInfoRep
            , SqlSugarRepository<cts_OrganizationAssessResult> resultRep
            , SqlSugarRepository<cts_OrganizationImg> orgImgRep
            , SqlSugarRepository<cts_AssessOrgImg> assessOrgImgRep
            , SqlSugarRepository<cts_OrgAssessBedImg> bedImgRep
            , SqlSugarRepository<cts_OrgAssessBedType> bedTypeRep
            , SqlSugarRepository<cts_OrgAssessServiceType> serviceTypeRep
            , SqlSugarRepository<cts_OrgAssessServiceImg> serviceImgRep
            , SqlSugarRepository<cts_OrgAssessServiceBasicType> basicTypeRep
            , SqlSugarRepository<cts_OrgAssessServiceBasicImg> basicImgRep

              , SqlSugarRepository<cts_OrgAssessSafeType> safeTypeRep
            , SqlSugarRepository<cts_OrgAssessSafeImg> safeImgRep

            , SqlSugarRepository<cts_Employee> employeeRep)
        {
            _assessTypeRep = assessTypeRep;
            _groupRep = groupRep;
            _orgRep = orgRep;
            _assessInfoRep = assessInfoRep;
            _bedInfoRep = bedInfoRep;
            _basicInfoRep = basicInfoRep;
            _safeInfoRep = safeInfoRep;
            _serviceInfoRep = serviceInfoRep;
            _resultRep = resultRep;
            _orgImgRep = orgImgRep;
            _assessOrgImgRep= assessOrgImgRep;
            _bedTypeRep = bedTypeRep;
            _bedImgRep= bedImgRep;
            _serviceTypeRep = serviceTypeRep;
            _serviceImgRep= serviceImgRep;
            _basicTypeRep= basicTypeRep;
            _basicImgRep= basicImgRep;
            _safeTypeRep= safeTypeRep;
            _safeImgRep = safeImgRep;


            _employeeRep = employeeRep;
        }

        /// <summary>
        /// 查询等级评定项目
        /// </summary>
        public List<cts_OrganizationAssessType> GetOrgAssessType()
        {
            return _assessTypeRep.AsQueryable().OrderBy(m => m.OrderIndex).ToList();
        }
        /// <summary>
        /// 删除等级评定项目
        /// </summary>
        /// <param name="gid"></param>
        public void DeleteOrgAssessType(string gid)
        {
            _assessTypeRep.AsUpdateable().SetColumns(m => m.sys_IsDelete == 1).Where(m => m.Gid == gid).ExecuteCommand();
        }

        /// <summary>
        /// 保存等级评定项目
        /// </summary>
        /// <param name="input"></param>
        public void SaveOrgAssessType(cts_OrganizationAssessType input)
        {
            if (input.Id > 0)
            {
                _assessTypeRep.Update(input);

            }
            else
            {
                input.Gid = Guid.NewGuid().ToString();
                _assessTypeRep.Insert(input);
            }
        }
        /// <summary>
        /// 导入等级评定项目
        /// </summary>
        /// <param name="list"></param>
        public void ImportOrgAssessType(List<ImportOrgAssessType> list)
        {
            List<cts_OrganizationAssessType> listInfo = new List<cts_OrganizationAssessType>();
            var parentType = "";
            var parentType2 = "";
            var parentType3 = "";
            foreach (var item in list)
            {
                cts_OrganizationAssessType oa = new cts_OrganizationAssessType
                {
                    Gid = Guid.NewGuid().ToString(),
                    Name = item.评定项目,
                    NoStr = item.序号,
                    Deduct = item.扣分项
                };
                if (!string.IsNullOrEmpty(item.分项总分) && !string.IsNullOrEmpty(item.分项总分.Trim()))
                {
                    parentType = item.评定项目;
                    oa.LevelType = 1;
                    oa.MaxScore = Util.Str2Decimal(item.分项总分.Trim());
                }
                else if (!string.IsNullOrEmpty(item.次分项总分) && !string.IsNullOrEmpty(item.次分项总分.Trim()))
                {
                    parentType2 = item.评定项目;
                    oa.LevelType = 2;
                    oa.ParentType = parentType;
                    oa.MaxScore = Util.Str2Decimal(item.次分项总分.Trim());
                }
                else if (!string.IsNullOrEmpty(item.三级项分值) && !string.IsNullOrEmpty(item.三级项分值.Trim()))
                {
                    parentType3 = item.评定项目;
                    oa.LevelType = 3;
                    oa.ParentType = parentType;
                    oa.ParentType2 = parentType2;
                    oa.MaxScore = Util.Str2Decimal(item.三级项分值.Trim());
                }
                else if (!string.IsNullOrEmpty(item.四级项分值) && !string.IsNullOrEmpty(item.四级项分值.Trim()))
                {
                    oa.LevelType = 4;
                    oa.ParentType = parentType;
                    oa.ParentType2 = parentType2;
                    oa.ParentType3 = parentType3;
                    oa.MaxScore = Util.Str2Decimal(item.四级项分值.Trim());
                }
                oa.AssessDesc = item.操作说明;
                oa.sys_IsDelete = 0;
                listInfo.Add(oa);
            }

            _assessTypeRep.InsertRange(listInfo);
        }


        /// <summary>
        /// 新建一个机构空项目
        /// </summary>     
        /// <returns></returns>
        public void SaveOrgGroup(cts_OrganizationGroup pGroup)
        {

            pGroup.Gid = Guid.NewGuid().ToString();
            _groupRep.Insert(pGroup);
        }
        /// <summary>
        /// 导入评定机构
        /// </summary>     
        /// <returns></returns>
        [UnitOfWork]
        public void ImportAssessOrg(ImportOrg importProp)
        {

            var cEmp = _employeeRep.GetFirst(m => m.Gid == UserHelper.GetUserId());
            var pGroup = importProp.pGroup;
            List<ImportOrgDesc> listError = new List<ImportOrgDesc>();
            var orderindex = 0;
            List<cts_AssessOrganization> listinfo = new List<cts_AssessOrganization>();
            var orderindexSave = _orgRep.AsQueryable().Where(m => m.GroupId == pGroup.Gid).Max(m => m.OrderIndex);

            foreach (var item in importProp.orgList)
            {
                orderindex += 1;
                orderindexSave += 1;
                cts_AssessOrganization cp = new cts_AssessOrganization();
                if (string.IsNullOrEmpty(item.名称))
                {
                    item.错误信息 = orderindex + ".信息不全：名称不能为空";
                    listError.Add(item);
                    continue;
                }
                cp.Gid = Guid.NewGuid().ToString();
                cp.sys_CreateDate = DateTime.Now;
                cp.sys_Creater = cEmp.Gid;
                cp.sys_CreaterName = cEmp.EmployeeName;
                cp.Name = item.名称;
                cp.LinkName = item.联系人;
                cp.LinkPhone = item.联系方式;
                cp.Address = item.地址;
                cp.State = 0;
                cp.GroupId = pGroup.Gid;
                cp.sys_IsDelete = 0;
                cp.OrderIndex = orderindexSave;
                listinfo.Add(cp);

            }

            if (listError.Count > 0)
            {
                throw Oops.Bah("操作失败").WithData(listError);
            }

            if (string.IsNullOrEmpty(pGroup.Gid))
            {
                pGroup.Gid = Guid.NewGuid().ToString();
                pGroup.sys_CreateDate = DateTime.Now;
                pGroup.sys_Creater = cEmp.Gid;
                pGroup.sys_CreaterName = cEmp.EmployeeName;
                _groupRep.Insert(pGroup);

            }
            _orgRep.InsertRange(listinfo);

        }


        /// <summary>
        /// 查询项目
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public SqlSugarPagedXList<cts_OrganizationGroup> SearchOrgGrouphasPage(SearchPersonGrouphasPageDto input)
        {

            // 构建子查询（B表）
            var subQuery = _orgRep.AsQueryable()
                .GroupBy(a => a.GroupId)
                .Select(a => new
                {
                    GroupId = a.GroupId,
                    OrgCount = SqlFunc.AggregateCount(0), // COUNT(0)
                    AssessCount = SqlFunc.AggregateSum(SqlFunc.IIF(a.State == 2, 1, 0)) // SUM(CASE WHEN State=2 THEN 1 ELSE 0 END)
                });

            // 主查询（A表左连接B表）
            return _groupRep.AsQueryable()
                 .LeftJoin(subQuery, (a, b) => a.Gid == b.GroupId)
                 .Where(a => a.IsSaved == input.issaved)
                 .WhereIF(!string.IsNullOrEmpty(input.str), a => a.GroupName.Contains(input.str))
                 .WhereIF(!string.IsNullOrEmpty(input.year), a => a.GroupYear.Equals(input.year))
                 .WhereIF(!string.IsNullOrEmpty(input.area), a => a.GroupArea.Equals(input.area))
                 .OrderByDescending(a => a.Id)
                 .Select((a, b) => new cts_OrganizationGroup
                 {
                     Id = a.Id.SelectAll(),
                     OrgCount = b.OrgCount,
                     AssessCount = b.AssessCount,

                 }).ToPagedList(input.page, input.size);
        }


        /// <summary>
        /// 查询机构
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public SqlSugarPagedXList<cts_AssessOrganization> SearchAssessOrg(SearchOrgDto input)
        {


            return _orgRep.AsQueryable()
                 .Where(m => m.GroupId == input.groupid)
                 .WhereIF(input.state > -1, m => m.State == input.state)
                 .WhereIF(!string.IsNullOrEmpty(input.str), m => m.Name.Contains(input.str))
                 .OrderByDescending(m => m.Id).ToPagedList(input.page, input.size);

        }
        /// <summary>
        /// 开始评定
        /// </summary>
        /// <param name="input"></param>
        public AssessOrganizationDto BeginOrgAssessByType(BeginAssessDto input)
        {
            var model = _orgRep.AsQueryable().Where(m => m.Gid == input.gid).Select<AssessOrganizationDto>().First();
            if (model == null)
            {
                throw Oops.Bah("未找到该机构信息");
            }
            var sqlSearchStr = "";

            if (input.leveltype == 1)
            {
                sqlSearchStr = $@"SELECT * FROM cts_OrganizationAssessInfo  A
                                    LEFT JOIN (
                                    SELECT ItemParentType,
	                                    SUM(CASE WHEN  SaveCount>0 THEN 1 ELSE 0 END) AS AssessCount,
	                                    SUM(CASE WHEN ItemLevelType=4  THEN 1 ELSE 0 END) AS ItemCount  
	                                    FROM cts_OrganizationAssessInfo  
                                    WHERE  sys_IsDelete = 0 AND OrganizationId = '{input.gid}' 
                                    AND ItemLevelType = 4 
                                    GROUP BY ItemParentType) B ON A.ItemName= B.ItemParentType
                                    WHERE A.sys_IsDelete = 0 AND A.OrganizationId = '{input.gid}' 
                                    AND A.ItemLevelType = 1   
                                    ORDER BY ItemOrderIndex
                                     ";
            }
            else if (input.leveltype == 2)
            {
                sqlSearchStr = $@"
                                        SELECT * FROM cts_OrganizationAssessInfo  A
                                        LEFT JOIN (
                                        SELECT ItemParentType2,
	                                        SUM(CASE WHEN  SaveCount>0 THEN 1 ELSE 0 END) AS AssessCount,
	                                        SUM(CASE WHEN ItemLevelType=4  THEN 1 ELSE 0 END) AS ItemCount  
	                                        FROM cts_OrganizationAssessInfo  
                                        WHERE  sys_IsDelete = 0 AND OrganizationId = '{input.gid}' 
                                        AND ItemLevelType = 4 AND ItemParentType='{input.parenttype}'
                                        GROUP BY ItemParentType2) B ON A.ItemName= B.ItemParentType2
                                        WHERE A.sys_IsDelete = 0 AND A.OrganizationId = '{input.gid}' 
                                        AND A.ItemLevelType = 2 AND  A.ItemParentType='{input.parenttype}'

                                        ORDER BY ItemOrderIndex
 
                                     ";
            }
            else
            {
                sqlSearchStr = $@"
                                        SELECT * FROM cts_OrganizationAssessInfo 
                                        WHERE sys_IsDelete = 0 AND OrganizationId = '{input.gid}' 
                                        AND (ItemLevelType = 3 OR ItemLevelType=4) 
                                        AND  ItemParentType='{input.parenttype}'
                                        AND  ItemParentType2='{input.parenttype2}'
                                        ORDER BY ItemOrderIndex 
 
                                     ";


            }

            var listinfo = _orgRep.AsSugarClient().Ado.SqlQuery<cts_OrganizationAssessInfo>(sqlSearchStr).ToList();

            if (listinfo != null && listinfo.Count > 0)
            {
                model.info = listinfo;
                return model;
            }
            else
            {

                var list = _assessTypeRep.AsQueryable().OrderBy(m => m.OrderIndex).ToList();
                var infoList = new List<cts_OrganizationAssessInfo>();
                var savedSql = Guid.NewGuid().ToString();
                foreach (var item in list)
                {
                    var info = new cts_OrganizationAssessInfo
                    {
                        Gid = Guid.NewGuid().ToString(),
                        sys_IsDelete = 0,
                        OrganizationId = model.Gid,
                        OrganizationName = model.Name,
                        SavedSql = savedSql,
                        ItemId = item.Gid,
                        ItemName = item.Name,
                        ItemNoStr = item.NoStr,
                        ItemMaxScore = item.MaxScore,
                        ItemLevelType = item.LevelType,
                        ItemOrderIndex = item.OrderIndex,
                        ItemParentType = item.ParentType,
                        ItemParentType2 = item.ParentType2,
                        ItemParentType3 = item.ParentType3,
                        ItemDeduct = item.Deduct,
                        ItemGrade = item.Grade,
                        ItemJoined = item.Joined,
                        ItemIsJoined = 1
                    };
                    infoList.Add(info);
                }
                _assessInfoRep.InsertRange(infoList);

                if (input.leveltype == 1)
                {
                    model.info = infoList.FindAll(m => m.ItemLevelType == 1);
                }
                else if (input.leveltype == 2)
                {
                    model.info = infoList.FindAll(m => m.ItemLevelType == 2 && m.ItemParentType == input.parenttype);
                }
                else
                {
                    model.info = infoList.FindAll(m => (m.ItemLevelType == 3 || m.ItemLevelType == 4) && m.ItemParentType == input.parenttype && m.ItemParentType2 == input.parenttype2);
                }
                return model;

            }
        }

        /// <summary>
        /// 获取评定内容
        /// </summary>
        /// <param name="gid"></param>
        public AssessOrganizationDto GetOrgAssess(string gid)
        {


            var model = _orgRep.AsQueryable().LeftJoin<cts_OrganizationAssessResult>((a, b) => a.Gid == b.OrganizationId)
                .Where(m => m.Gid == gid).Select((a, b) => new AssessOrganizationDto
                {
                    Id = a.Id.SelectAll(),
                    finalresult = b
                }).First();

            if (model == null)
            {
                throw Oops.Bah("未找到该机构信息");
            }
            //机构评定信息
            var listinfo = _assessInfoRep.AsQueryable().Where(m => m.OrganizationId == gid).OrderBy(m => m.ItemOrderIndex).ToList();
            model.info = listinfo;

            //床位评定
            var listbedinfo = _bedInfoRep.AsQueryable().Where(m => m.OrganizationId == gid).OrderBy(m => m.ItemOrderIndex).ToList();
            model.bedinfo = listbedinfo;

            //服务质量大检查
            var listserviceinfo = _serviceInfoRep.AsQueryable().Where(m => m.OrganizationId == gid).OrderBy(m => m.ItemOrderIndex).ToList();
            model.serviceinfo = listserviceinfo;

            //服务质量基本规范 
            var listbasicinfo = _basicInfoRep.AsQueryable().Where(m => m.OrganizationId == gid).OrderBy(m => m.ItemOrderIndex).ToList();

            model.servicebasicinfo = listbasicinfo;

            //服务安全基本规范
            var listsafeinfo = _safeInfoRep.AsQueryable().Where(m => m.OrganizationId == gid).OrderBy(m => m.ItemOrderIndex).ToList();

            model.safeinfo = listsafeinfo;
            return model;
        }

        /// <summary>
        /// 保存评定结论
        /// </summary>     
        /// <returns></returns>
        public string SaveOrgFinalResult(cts_OrganizationAssessResult info)
        {
            var model = _resultRep.GetFirst(m => m.OrganizationId == info.OrganizationId);
            if (model == null)
            {
                info.Gid = Guid.NewGuid().ToString();
                _resultRep.Insert(info);
                return info.Gid;
            }
            else
            {
                _resultRep.AsUpdateable(info).IgnoreColumns(m => m.NurseBed).ExecuteCommand();
                return info.Gid;
            }

        }

        /// <summary>
        /// 保存评定护理床位数量
        /// </summary>     
        /// <returns></returns> 
        public string SaveOrgNurseBed(cts_OrganizationAssessResult info)
        {
            var model = _resultRep.GetFirst(m => m.OrganizationId == info.OrganizationId);
            if (model == null)
            {
                info.Gid = Guid.NewGuid().ToString();
                _resultRep.Insert(info);
                return info.Gid;
            }
            else
            {
                _resultRep.AsUpdateable(info).IgnoreColumns(m => m.FinalResult).ExecuteCommand();
                return info.Gid;
            }
        }

        /// <summary>
        /// 获取评定结论
        /// </summary>
        /// <param name="gid"></param>
        /// <returns></returns>
        public cts_OrganizationAssessResult GetFinalResultByOrgId(string gid)
        {
            return _resultRep.GetFirst(m => m.OrganizationId == gid);
        }
        /// <summary>
        /// 保存最终评定结论
        /// </summary>
        /// <param name="gid"></param>
        [UnitOfWork]
        public void SaveOrgAssessRst(string gid)
        {
            var cEmp = _employeeRep.GetFirst(m => m.Gid == UserHelper.GetUserId());

            if (cEmp.Auth != (cEmp.Auth | 1))
            {
                throw Oops.Bah("无权限");
            }
            string[] parentNames = { "环境", "设施设备", "运营管理", "服务" };
            List<string> notjoinedNoStr = new List<string>();
            //不参与评分积分；
            decimal notjoinedAmount1 = 0;
            decimal notjoinedAmount2 = 0;
            decimal notjoinedAmount3 = 0;
            decimal notjoinedAmount4 = 0;

            decimal amount214 = 0;
            decimal amount232 = 0;
            var model = _orgRep.GetFirst(m => m.Gid == gid);
            if (model == null)
            {
                throw Oops.Bah("未找到该机构信息");
            }
            if (model.StartTime == null)
            {
                throw Oops.Bah("运营年月不能为空");
            }

            var listinfo = _assessInfoRep.AsQueryable().Where(m => m.OrganizationId == gid).OrderBy(m => m.ItemOrderIndex).ToList();

            decimal amount = 0;
            decimal amount1Max = 0;
            decimal amount2Max = 0;
            decimal amount3Max = 0;
            decimal amount4Max = 0;
            decimal amount1 = 0;
            decimal amount2 = 0;
            decimal amount3 = 0;
            decimal amount4 = 0;
            int maxLevel = 5;

            bool b4_1 = false;
            bool b4_2 = false;
            bool b4_3 = false;
            bool b4_4 = false;
            bool b4_5 = false;
            bool b4_6 = false;
            bool b4_7 = false;
            bool b4_8 = false;
            bool b4_9 = false;
            bool b4_10 = false;
            bool b4_11 = false;
            bool b4_12 = false;
            bool b4_13 = false;
            List<cts_OrganizationAssessInfo> parentType = new List<cts_OrganizationAssessInfo>();
            List<cts_OrganizationAssessInfo> parentType2 = new List<cts_OrganizationAssessInfo>();
            List<cts_OrganizationAssessInfo> parentType3 = new List<cts_OrganizationAssessInfo>();
            foreach (var item in listinfo)
            {
                if (item.ItemLevelType == 4)
                {
                    if (item.ItemParentType.Equals(parentNames[0]))
                    {
                        if (item.ItemJoined == 1 && item.ItemIsJoined == 0)
                        {
                            notjoinedAmount1 += item.ItemMaxScore;
                            notjoinedNoStr.Add(item.ItemNoStr);
                        }
                        else
                        {
                            amount1 += item.FinalScore;
                        }

                        if (item.ItemNoStr.Equals("1.4.3.2"))
                        {

                            if (item.FinalScore < 1)
                            {
                                if (maxLevel > 3)
                                {
                                    maxLevel = 3;
                                }

                            }
                        }
                        if (item.ItemNoStr.Equals("1.4.3.6"))
                        {

                            if (item.FinalScore < 1)
                            {
                                if (maxLevel > 3)
                                {
                                    maxLevel = 3;
                                }

                            }
                        }


                    }
                    else if (item.ItemParentType.Equals(parentNames[1]))
                    {
                        if (item.ItemJoined == 1 && item.ItemIsJoined == 0)
                        {
                            notjoinedAmount2 += item.ItemMaxScore;
                            notjoinedNoStr.Add(item.ItemNoStr);
                        }
                        else
                        {
                            amount2 += item.FinalScore;
                            if (item.ItemNoStr.StartsWith("2.1.4."))
                            {
                                amount214 += item.FinalScore;
                            }
                            if (item.ItemNoStr.StartsWith("2.3.2."))
                            {
                                amount232 += item.FinalScore;
                            }
                        }
                        if (item.ItemNoStr.Equals("2.1.1.2"))
                        {
                            if (item.FinalScore < 1)
                            {
                                if (maxLevel > 3)
                                {
                                    maxLevel = 3;
                                }
                            }

                        }
                        if (item.ItemNoStr.Equals("2.1.2.1"))
                        {
                            if (item.FinalScore < 2)
                            {
                                if (maxLevel > 4)
                                {
                                    maxLevel = 4;
                                }

                            }
                            if (item.FinalScore < 1)
                            {
                                if (maxLevel > 3)
                                {
                                    maxLevel = 3;
                                }

                            }
                            if (item.FinalScore < 0.5M)
                            {
                                if (maxLevel > 2)
                                {
                                    maxLevel = 2;
                                }
                            }
                        }
                        if (item.ItemNoStr.Equals("2.2.1.7"))
                        {

                            if (item.FinalScore < 1)
                            {
                                if (maxLevel > 3)
                                {
                                    maxLevel = 3;
                                }

                            }
                        }
                        if (item.ItemNoStr.Equals("2.5.1.2"))
                        {

                            if (item.FinalScore < 1)
                            {
                                if (maxLevel > 2)
                                {
                                    maxLevel = 2;
                                }

                            }
                        }


                    }
                    else if (item.ItemParentType.Equals(parentNames[2]))
                    {
                        if (item.ItemJoined == 1 && item.ItemIsJoined == 0)
                        {
                            notjoinedAmount3 += item.ItemMaxScore;
                            notjoinedNoStr.Add(item.ItemNoStr);
                        }
                        else
                        {
                            amount3 += item.FinalScore;
                        }

                        if (item.ItemNoStr.Equals("3.2.3.1"))
                        {
                            if (item.FinalScore < 1.5M)
                            {
                                if (maxLevel > 3)
                                {
                                    maxLevel = 3;
                                }
                            }
                            if (item.FinalScore < 1)
                            {
                                if (maxLevel > 2)
                                {
                                    maxLevel = 2;
                                }
                            }
                            if (item.FinalScore < 0.5M)
                            {
                                maxLevel = 0;
                            }

                        }
                        if (item.ItemNoStr.Equals("3.2.3.3"))
                        {
                            if (item.FinalScore < 1)
                            {
                                if (maxLevel > 3)
                                {
                                    maxLevel = 3;
                                }
                            }
                            if (item.FinalScore < 0.5M)
                            {
                                if (maxLevel > 2)
                                {
                                    maxLevel = 2;
                                }
                            }


                        }
                    }
                    else if (item.ItemParentType.Equals(parentNames[3]))
                    {

                        if (item.ItemJoined == 1 && item.ItemIsJoined == 0)
                        {
                            notjoinedAmount4 += item.ItemMaxScore;
                            notjoinedNoStr.Add(item.ItemNoStr);
                        }
                        else
                        {
                            amount4 += item.FinalScore;
                        }

                        if (item.ItemNoStr.Equals("4.1.3.13"))
                        {
                            if (item.FinalScore < 5)
                            {
                                if (maxLevel > 4)
                                {
                                    maxLevel = 4;
                                }
                            }
                            if (item.FinalScore < 4)
                            {
                                if (maxLevel > 3)
                                {
                                    maxLevel = 3;
                                }
                            }
                            if (item.FinalScore < 3)
                            {
                                if (maxLevel > 2)
                                {
                                    maxLevel = 2;
                                }
                            }
                            if (item.FinalScore < 2)
                            {
                                if (maxLevel > 1)
                                {
                                    maxLevel = 1;
                                }
                            }
                            if (item.FinalScore < 1)
                            {
                                maxLevel = 0;
                            }
                        }

                        if (item.ItemNoStr.StartsWith("4.1.") && item.FinalScore > 0)
                        {
                            b4_1 = true;
                        }
                        if (item.ItemNoStr.StartsWith("4.2.") && item.FinalScore > 0)
                        {
                            b4_2 = true;
                        }
                        if (item.ItemNoStr.StartsWith("4.3.") && item.FinalScore > 0)
                        {
                            b4_3 = true;
                        }
                        if (item.ItemNoStr.StartsWith("4.4.") && item.FinalScore > 0)
                        {
                            b4_4 = true;
                        }
                        if (item.ItemNoStr.StartsWith("4.5.") && item.FinalScore > 0)
                        {
                            b4_5 = true;
                        }
                        if (item.ItemNoStr.StartsWith("4.6.") && item.FinalScore > 0)
                        {
                            b4_6 = true;
                        }
                        if (item.ItemNoStr.StartsWith("4.7.") && item.FinalScore > 0)
                        {
                            b4_7 = true;
                        }
                        if (item.ItemNoStr.StartsWith("4.8.") && item.FinalScore > 0)
                        {
                            b4_8 = true;
                        }
                        if (item.ItemNoStr.StartsWith("4.9.") && item.FinalScore > 0)
                        {
                            b4_9 = true;
                        }
                        if (item.ItemNoStr.StartsWith("4.10.") && item.FinalScore > 0)
                        {
                            b4_10 = true;
                        }
                        if (item.ItemNoStr.StartsWith("4.11.") && item.FinalScore > 0)
                        {
                            b4_11 = true;
                        }
                        if (item.ItemNoStr.StartsWith("4.12.") && item.FinalScore > 0)
                        {
                            b4_12 = true;
                        }
                        if (item.ItemNoStr.StartsWith("4.13.") && item.FinalScore > 0)
                        {
                            b4_13 = true;
                        }
                    }

                    if (item.ItemGrade == 1 && item.FinalScore < item.ItemMaxScore)
                    {

                        if (item.ItemNoStr.Equals("1.4.3.2")
                            || item.ItemNoStr.Equals("1.4.3.6")

                            || item.ItemNoStr.Equals("2.1.1.2")
                            || item.ItemNoStr.Equals("2.1.2.1")
                            || item.ItemNoStr.Equals("2.2.1.7")
                            || item.ItemNoStr.Equals("2.5.1.2")

                            || item.ItemNoStr.Equals("3.2.3.1")
                            || item.ItemNoStr.Equals("3.2.3.3")

                            || item.ItemNoStr.Equals("4.1.3.13"))
                        {

                        }
                        else if (item.ItemJoined == 1 && item.ItemIsJoined == 0)
                        {

                        }
                        else
                        {
                            maxLevel = 0;
                        }

                    }
                }
                else if (item.ItemLevelType == 3)
                {
                    parentType3.Add(item);
                    if (item.ItemJoined == 1 && item.ItemIsJoined == 0 && (item.ItemNoStr.Equals("2.1.4") || item.ItemNoStr.Equals("2.3.2")))
                    {
                        notjoinedAmount2 += item.ItemMaxScore;
                        notjoinedNoStr.Add(item.ItemNoStr);
                    }

                }
                else if (item.ItemLevelType == 2)
                {
                    parentType2.Add(item);
                }
                else if (item.ItemLevelType == 1)
                {
                    parentType.Add(item);
                    if (item.ItemName.Equals(parentNames[0]))
                    {
                        amount1Max = item.ItemMaxScore;
                    }
                    else if (item.ItemName.Equals(parentNames[1]))
                    {
                        amount2Max = item.ItemMaxScore;
                    }
                    else if (item.ItemName.Equals(parentNames[2]))
                    {
                        amount3Max = item.ItemMaxScore;
                    }
                    else if (item.ItemName.Equals(parentNames[3]))
                    {
                        amount4Max = item.ItemMaxScore;
                    }
                }

            }

            if (notjoinedAmount1 > 0)//环境部分有不参与评分的项目
            {
                amount1 = Math.Round(amount1 / (amount1Max - notjoinedAmount1) * amount1Max, 2);
            }
            if (notjoinedAmount2 > 0)//设施设备有不参与评分的项目
            {
                if (notjoinedNoStr.Contains("2.1.4"))
                {
                    amount2 -= amount214;
                }
                if (notjoinedNoStr.Contains("2.3.2"))
                {
                    amount2 -= amount232;
                }
                amount2 = Math.Round(amount2 / (amount2Max - notjoinedAmount2) * amount2Max, 2);
            }
            if (notjoinedAmount3 > 0)
            {
                amount3 = Math.Round(amount3 / (amount3Max - notjoinedAmount3) * amount3Max, 2);
            }
            if (notjoinedAmount4 > 0)
            {
                amount4 = Math.Round(amount4 / (amount4Max - notjoinedAmount4) * amount4Max, 2);
            }

            if (amount1 < (amount1Max * 0.9m)
                    || amount2 < (amount2Max * 0.9m)
                    || amount3 < (amount3Max * 0.9m)
                    || amount4 < (amount4Max * 0.9m))
            {
                if (maxLevel > 4)
                {
                    maxLevel = 4;
                }
            }
            if (amount1 < (amount1Max * 0.8m)
               || amount2 < (amount2Max * 0.8m)
               || amount3 < (amount3Max * 0.8m)
               || amount4 < (amount4Max * 0.8m))
            {
                if (maxLevel > 3)
                {
                    maxLevel = 3;
                }
            }
            if (amount1 < (amount1Max * 0.6m)
             || amount2 < (amount2Max * 0.6m)
             || amount3 < (amount3Max * 0.6m)
             || amount4 < (amount4Max * 0.6m))
            {
                if (maxLevel > 2)
                {
                    maxLevel = 2;
                }
            }

            if (amount1 < (amount1Max * 0.5m)
             || amount2 < (amount2Max * 0.5m)
             || amount3 < (amount3Max * 0.5m)
             || amount4 < (amount4Max * 0.5m))
            {
                if (maxLevel > 1)
                {
                    maxLevel = 1;
                }
            }
            if (amount1 < (amount1Max * 0.4m)
            || amount2 < (amount2Max * 0.4m)
            || amount3 < (amount3Max * 0.4m)
            || amount4 < (amount4Max * 0.4m))
            {
                maxLevel = 0;
            }
            amount = Math.Round(amount1 + amount2 + amount3 + amount4, 2);
            if (model.OldPerson < 1 || model.BedCount < 1)
            {
                maxLevel = 0;
            }
            else
            {
                var liveRate = model.OldPerson * 1.0 / model.BedCount;
                if (liveRate < 0.3)
                {
                    maxLevel = 0;
                }
                else if (liveRate < 0.35)
                {
                    if (maxLevel > 1)
                    {
                        maxLevel = 1;
                    }
                }
                else if (liveRate < 0.4)
                {
                    if (maxLevel > 2)
                    {
                        maxLevel = 2;
                    }
                }
                else if (liveRate < 0.45)
                {

                    if (maxLevel > 3)
                    {
                        maxLevel = 3;
                    }
                }
                else if (liveRate < 0.5)
                {

                    if (maxLevel > 4)
                    {
                        maxLevel = 4;
                    }
                }

            }

            if (amount >= 900)
            {

            }
            else if (amount >= 780)
            {
                if (maxLevel > 4)
                {
                    maxLevel = 4;
                }
            }
            else if (amount >= 570)
            {
                if (maxLevel > 3)
                {
                    maxLevel = 3;
                }
            }
            else if (amount >= 450)
            {
                if (maxLevel > 2)
                {
                    maxLevel = 2;
                }
            }
            else if (amount >= 360)
            {
                if (maxLevel > 1)
                {
                    maxLevel = 1;
                }
            }
            else
            {
                maxLevel = 0;
            }
            if (model.CheckTime == null)
            {
                model.CheckTime = DateTime.Now;
            }
            if (!Util.MoreOneYear((DateTime)model.StartTime, (DateTime)model.CheckTime))
            {
                maxLevel = 0;
            }
            if (b4_1 && b4_2 && b4_3 && b4_4 && b4_5 && b4_6 && b4_7 && b4_8 && b4_9 && b4_10)
            {
                if (b4_11 && b4_12 && b4_13)
                {

                }
                else if (b4_11 && b4_12)
                {
                    if (maxLevel > 4)
                    {
                        maxLevel = 4;
                    }
                }
                else if (b4_11)
                {
                    if (maxLevel > 3)
                    {
                        maxLevel = 3;
                    }
                }
                else
                {
                    if (maxLevel > 2)
                    {
                        maxLevel = 2;
                    }
                }


            }
            else
            {
                maxLevel = 0;
            }
            model.FinalLevel = maxLevel;
            if (string.IsNullOrEmpty(model.CheckPerson))
            {
                model.CheckPerson = cEmp.Gid;
                model.CheckPersonName = cEmp.EmployeeName;

            }

            model.State = 2;
            model.FinalScore = amount;
            var sqlUpdateAll1 = $@"UPDATE cts_OrganizationAssessInfo SET FinalScore={amount1}  WHERE OrganizationId='{model.Gid}'  AND ItemLevelType=1  AND ItemName='{parentNames[0]}'";
            var sqlUpdateAll2 = $@"UPDATE cts_OrganizationAssessInfo SET FinalScore={amount2}  WHERE OrganizationId='{model.Gid}'  AND ItemLevelType=1  AND ItemName='{parentNames[1]}'";
            var sqlUpdateAll3 = $@"UPDATE cts_OrganizationAssessInfo SET FinalScore={amount3}  WHERE OrganizationId='{model.Gid}'  AND ItemLevelType=1  AND ItemName='{parentNames[2]}'";
            var sqlUpdateAll4 = $@"UPDATE cts_OrganizationAssessInfo SET FinalScore={amount4}  WHERE OrganizationId='{model.Gid}'  AND ItemLevelType=1  AND ItemName='{parentNames[3]}'";
            var sqlUpdate2 = $@"UPDATE A SET FinalScore= B.FinalScore FROM [cts_OrganizationAssessInfo] A,
  ( SELECT ItemParentType,ItemParentType2,SUM(FinalScore) AS FinalScore FROM [cts_OrganizationAssessInfo]
  WHERE OrganizationId='{model.Gid}' AND ItemLevelType=4
  GROUP BY ItemParentType,ItemParentType2 ) B 
  WHERE A.OrganizationId='{model.Gid}' AND A.ItemLevelType=2 AND A.ItemName=B.ItemParentType2 AND A.ItemParentType=B.ItemParentType";
            var sqlUpdate3 = $@"UPDATE A SET FinalScore= B.FinalScore FROM [cts_OrganizationAssessInfo] A,
  (  SELECT ItemParentType,ItemParentType2,ItemParentType3,SUM(FinalScore) AS FinalScore FROM [cts_OrganizationAssessInfo]
  WHERE OrganizationId='{model.Gid}' AND ItemLevelType=4
  GROUP BY ItemParentType,ItemParentType2,ItemParentType3) B 
  WHERE A.OrganizationId='{model.Gid}' AND A.ItemLevelType=3 AND A.ItemName=B.ItemParentType3 AND A.ItemParentType2=B.ItemParentType2 AND A.ItemParentType=B.ItemParentType";


            _orgRep.Update(model);
            _orgRep.AsSugarClient().Ado.ExecuteCommand(sqlUpdateAll1);
            _orgRep.AsSugarClient().Ado.ExecuteCommand(sqlUpdateAll2);
            _orgRep.AsSugarClient().Ado.ExecuteCommand(sqlUpdateAll3);
            _orgRep.AsSugarClient().Ado.ExecuteCommand(sqlUpdateAll4);
            _orgRep.AsSugarClient().Ado.ExecuteCommand(sqlUpdate2);
            _orgRep.AsSugarClient().Ado.ExecuteCommand(sqlUpdate3);



        }


        /// <summary>
        /// 保存单个评定项目
        /// </summary>
        /// <param name="item"></param>
        [UnitOfWork]
        public void SaveOrgAssessItem(cts_OrganizationAssessInfo item)
        {
            var cEmp = _employeeRep.GetFirst(m => m.Gid == UserHelper.GetUserId());

            if (cEmp.Auth != (cEmp.Auth | 1))
            {
                throw Oops.Bah("无权限");
            }
            var model = _orgRep.GetFirst(m => m.Gid == item.OrganizationId);
            if (model == null)
            {
                throw Oops.Bah("未找到该机构信息");
            }
            if (model.State == 0)
            {
                model.CheckPerson = cEmp.Gid;
                model.CheckPersonName = cEmp.EmployeeName;
                model.CheckTime = DateTime.Now;
                model.State = 1;
            }
            else
            {
                model.sys_Modifier = cEmp.Gid;
                model.sys_ModifierName = cEmp.EmployeeName;
                model.sys_ModifyDate = DateTime.Now;
            }
            if (item.SaveCount == 0)
            {
                item.sys_Creater = cEmp.Gid;
                item.sys_CreaterName = cEmp.EmployeeName;
                item.sys_CreateDate = DateTime.Now;
            }
            else
            {
                item.sys_Modifier = cEmp.Gid;
                item.sys_ModifierName = cEmp.EmployeeName;
                item.sys_ModifyDate = DateTime.Now;
            }
            item.SaveCount += 1;
            _orgRep.Update(model);
            _assessInfoRep.Update(item);

        }

        /// <summary>
        /// 查询乡镇
        /// </summary>
        /// <param name="groupid"></param>
        /// <returns></returns>
        public List<string> GetOrgTown(string groupid)
        {
            return _orgRep.AsQueryable().Where(m => m.GroupId == groupid && !string.IsNullOrEmpty(m.Town)).Select(m => m.Town).Distinct().ToList();

        }
        /// <summary>
        /// 转移机构
        /// </summary>
        /// <param name="input"></param>
        public void TransOrgGroup(TransOrgInput input)
        {
            _orgRep.AsUpdateable().SetColumns(m => new cts_AssessOrganization { GroupId = input.groupid, Town = input.town }).Where(m => m.Gid == input.gid).ExecuteCommand();
        }
        /// <summary>
        /// 存档
        /// </summary>
        /// <param name="gid"></param>
        public void SavedOrgGroup(string gid)
        {

            _groupRep.AsUpdateable().SetColumns(m => m.IsSaved == 1).Where(m => m.Gid == gid).ExecuteCommand();
        }
        /// <summary>
        /// 删除项目
        /// </summary>
        /// <param name="gid"></param>
        public void DeleteOrgGroup(string gid)
        {
            _groupRep.AsUpdateable().SetColumns(m => m.sys_IsDelete == 1).Where(m => m.Gid == gid).ExecuteCommand();
        }

        /// <summary>
        /// 删除机构
        /// </summary>
        /// <param name="gid"></param>
        public void DeleteAssessOrg(string gid)
        {
            _orgRep.AsUpdateable().SetColumns(m => m.sys_IsDelete == 1).Where(m => m.Gid == gid).ExecuteCommand();
        }

        /// <summary>
        /// 保存机构
        /// </summary>
        /// <param name="info"></param>
        public string SaveAssessOrg(AssessOrganizationDto info)
        {

            if (info.StartTime == null)
            {
                throw Oops.Bah("运营年月不能为空");
            }

            // 新增操作
            if (string.IsNullOrEmpty(info.Gid))
            {
                // 获取最大排序号
                var orderIndex = _orgRep.AsQueryable()
                    .Where(m => m.GroupId == info.GroupId)
                    .Max(m => m.OrderIndex);

                // 设置新增实体属性
                info.Gid = Guid.NewGuid().ToString();
                info.OrderIndex = orderIndex + 1;

                // 插入主表
                _orgRep.Insert(info);

                // 处理图片
                if (info.imgs != null && info.imgs.Any())
                {
                    foreach (var img in info.imgs)
                    {
                        img.Gid = Guid.NewGuid().ToString();
                        img.OrganizationId = info.Gid;


                    }
                    _orgImgRep.InsertRange(info.imgs);
                }


            }
            // 编辑操作
            else
            {
                _orgRep.AsUpdateable(info).IgnoreColumns(m => m.OrderIndex)
                    .Where(m => m.Gid == info.Gid)
                    .ExecuteCommand();

                // 删除旧图片
                _orgImgRep.Delete(m => m.OrganizationId == info.Gid);

                // 插入新图片
                if (info.imgs != null && info.imgs.Any())
                {
                    foreach (var img in info.imgs)
                    {
                        img.Gid = Guid.NewGuid().ToString();
                        img.OrganizationId = info.Gid;

                    }
                    _orgImgRep.InsertRange(info.imgs);
                }

            }
            return info.Gid;
        }

        /// <summary>
        /// 获取机构
        /// </summary>
        /// <param name="gid"></param>
        /// <returns></returns>
        public AssessOrganizationDto GetAssessOrgById(string gid)
        {
            var info = _orgRep.AsQueryable().Where(m => m.Gid == gid).Select<AssessOrganizationDto>().First();
            info.imgs = _orgImgRep.GetList(m => m.OrganizationId == gid);
            return info;
        }

        /// <summary>
        /// 删除评定项目图片
        /// </summary>
        /// <param name="gid"></param>
        public void DeleteOrgItemImg(string gid)
        {
            _assessOrgImgRep.AsUpdateable().SetColumns(m => m.sys_IsDelete == 1).Where(m => m.Gid == gid).ExecuteCommand();
        }
        /// <summary>
        /// 获取评定项目图片
        /// </summary>
        /// <param name="gid"></param>
        /// <returns></returns>
        public List<cts_AssessOrgImg> GetOrgItemImg(string gid)
        {

            return _assessOrgImgRep.GetList(m => m.OrgItemId == gid);
        }



        /// <summary>
        /// 获取评定报告年份地区
        /// </summary>     
        /// <returns></returns>
        [HttpGet]
        public List<MenuModel> GetAreaYear()
        {
            var sql = $"SELECT DISTINCT GroupYear AS YearName,GroupArea AS AreaName  FROM cts_OrganizationGroup WHERE IsSaved=1 ORDER BY GroupYear DESC";
            List<cts_Area_Year> list = _orgRep.AsSugarClient().Ado.SqlQuery<cts_Area_Year>(sql).ToList();
            var tmpYear = "";
            var finalList = new List<MenuModel>();
            var tmpMenu = new MenuModel();

            foreach (var item in list)
            {
                var tmpChild = new MenuChild();
                tmpChild.YearName = item.YearName;
                tmpChild.AreaName = item.AreaName;
                if (!item.YearName.Equals(tmpYear))
                {
                    tmpYear = item.YearName;
                    tmpMenu = new MenuModel();
                    tmpMenu.Area = new List<MenuChild>();
                    tmpMenu.Year = tmpYear;
                    finalList.Add(tmpMenu);
                }

                tmpMenu.Area.Add(tmpChild);
            }
            return finalList;   

        }




        #region 床位评定
        /// <summary>
        /// 查询床位评定项目
        /// </summary>     
        /// <returns></returns>
        [HttpGet]
        public List<cts_OrgAssessBedType> GetOrgAssessBedType()
        { 
            return _bedTypeRep.AsQueryable().OrderBy(m=>m.OrderIndex).ToList();
        }
        /// <summary>
        /// 删除床位评定项目
        /// </summary>     
        /// <returns></returns>
       
        public void DeleteOrgAssessBedType(string id)
        {
            _bedTypeRep.AsUpdateable().SetColumns(m => m.sys_IsDelete == 1).Where(m => m.Gid == id).ExecuteCommand();
        }
        /// <summary>
        /// 保存床位评定项目
        /// </summary>     
        /// <returns></returns>
        [HttpPost]
        public void SaveOrgAssessBedType(cts_OrgAssessBedType info)
        {
            //新增
            if (string.IsNullOrEmpty(info.Gid))
            {
                info.Gid = Guid.NewGuid().ToString();
                _bedTypeRep.Insert(info);

            }
            else {
                _bedTypeRep.Update(info);
            }
              
        }

        /// <summary>
        /// 导入床位评定项目
        /// </summary>     
        /// <returns></returns>
        [HttpPost]
        [UnitOfWork]
        public void ImportOrgAssessBedType(List<ImportXFYAssessType> list)
        {

            if (list == null || list.Count == 0)
            {

                throw Oops.Bah("导入数据不能为空"); 
            }
            List<cts_OrgAssessBedType> listinfo = new List<cts_OrgAssessBedType>();
            var index = 0;
            foreach (var item in list)
            {
                index += 1;
                cts_OrgAssessBedType oa = new cts_OrgAssessBedType
                {
                    Gid = Guid.NewGuid().ToString(),
                    Name = item.评定项目,
                    ParentType = item.一级分类,
                    ParentType2 = item.二级分类,
                    NoStr = item.序号,
                    OrderIndex = index,
                    IsTitle = item.是否为标题,
                    sys_IsDelete = 0
                };
                listinfo.Add(oa);
            }
            _bedTypeRep.Delete(m=>true);
            _bedTypeRep.InsertRange(listinfo);
        }
        /// <summary>
        /// 开始评定床位
        /// </summary>     
        /// <returns></returns>
        [HttpPost]
        public AssessOrganizationDto BeginOrgAssessBed(string gid)
        {
            var model = _orgRep.AsQueryable().Where(m => m.Gid == gid).Select<AssessOrganizationDto>().First();
            if (model == null)
            {
                throw Oops.Bah("未找到该机构信息");
            }
            var listinfo = _bedInfoRep.AsQueryable().Where(m => m.OrganizationId == gid).OrderBy(m => m.ItemOrderIndex).ToList();

            if (listinfo != null && listinfo.Count > 0)
            {
                model.bedinfo = listinfo;
            }
            else
            {
                var infoList = new List<cts_OrgAssessBedInfo>();

                var list = _bedTypeRep.AsQueryable().OrderBy(m => m.OrderIndex).ToList();
                var savedSql = Guid.NewGuid().ToString();
                foreach (var item in list)
                {
                    var info = new cts_OrgAssessBedInfo
                    {

                        sys_CreateDate = DateTime.Now,
                        Gid = Guid.NewGuid().ToString(),
                        sys_IsDelete = 0,
                        OrganizationId = model.Gid,
                        OrganizationName = model.Name,
                        SavedSql = savedSql,
                        ItemId = item.Gid,
                        ItemName = item.Name,
                        ItemNoStr = item.NoStr,
                        IsTitle = item.IsTitle,
                        ItemOrderIndex = item.OrderIndex,
                        ItemParentType = item.ParentType,
                        ItemParentType2 = item.ParentType2,
                        ItemParentType3 = item.ParentType3,
                        IsStandard = 0,
                    };
                    infoList.Add(info);
                }

                _bedInfoRep.InsertRange(infoList);
                model.bedinfo = infoList; 

            } 

            return model;
        }
        /// <summary>
        /// 保存单个床位评定
        /// </summary>     
        /// <returns></returns>
        [HttpPost]
        public cts_OrgAssessBedInfo SaveOrgBedAssessItem(cts_OrgAssessBedInfo item)
        {

            item.SaveCount += 1;
            _bedInfoRep.Update(item);
            return item;
        }


        /// <summary>
        /// 获取床位评定 
        /// </summary>     
        /// <returns></returns>
        [HttpGet]
        public List<cts_OrgAssessBedInfo> GetOrgBedAssess(string id)
        {
            return _bedInfoRep.GetList(m=>m.OrganizationId==id);
        }

       
        /// <summary>
        /// 删除床位图片
        /// </summary>     
        /// <returns></returns> 
        public void DeleteOrgBedItemImg(string gid)
        {
            _bedImgRep.AsUpdateable().SetColumns(m => m.sys_IsDelete == 1).Where(m => m.Gid == gid).ExecuteCommand();
        }
        /// <summary>
        /// 获取图片
        /// </summary>     
        /// <returns></returns>
        [HttpGet]
        public List<cts_OrgAssessBedImg> GetOrgBedItemImg(string gid)
        {
            return _bedImgRep.GetList(m => m.OrgItemId == gid);
        }

        #endregion

        #region 服务质量评定
        /// <summary>
        /// 查询服务评定项目
        /// </summary>     
        /// <returns></returns>
        [HttpGet]
        public List<cts_OrgAssessServiceType> GetOrgAssessServiceType()
        {

            return _serviceTypeRep.AsQueryable().OrderBy(m => m.OrderIndex).ToList();
        }
        /// <summary>
        /// 删除服务评定项目
        /// </summary>     
        /// <returns></returns>
       
        public void DeleteOrgAssessServiceType(string id)
        {
            _serviceTypeRep.AsUpdateable().SetColumns(m => m.sys_IsDelete == 1).Where(m => m.Gid == id).ExecuteCommand();
          
        }
        /// <summary>
        /// 保存服务评定项目
        /// </summary>     
        /// <returns></returns>
        [HttpPost]
        public void SaveOrgAssessServiceType(cts_OrgAssessServiceType info)
        {

            //新增
            if (string.IsNullOrEmpty(info.Gid))
            {
                info.Gid = Guid.NewGuid().ToString();
                _serviceTypeRep.Insert(info);

            }
            else
            {
                _serviceTypeRep.Update(info);
            }

        }

        /// <summary>
        /// 导入服务评定项目
        /// </summary>     
        /// <returns></returns>
        [HttpPost]
        public void ImportOrgAssessServiceType(List<ImportOrgAssessServiceType> list)
        {
            if (list == null || list.Count == 0)
            {

                throw Oops.Bah("导入数据不能为空");
            }
            List<cts_OrgAssessServiceType> listinfo = new List<cts_OrgAssessServiceType>();
            var index = 0;
            foreach (var item in list)
            {
                index += 1;
                cts_OrgAssessServiceType oa = new cts_OrgAssessServiceType
                {
                    Gid = Guid.NewGuid().ToString(),
                    Name = item.评定项目,
                    ParentType2 = item.评定说明,
                    NoStr = item.序号,
                    OrderIndex = index,
                    AssessDesc = item.操作说明,
                    Grade = item.是否重要,
                    sys_IsDelete = 0
                };
                listinfo.Add(oa);
            }
            _serviceTypeRep.Delete(m => true);
            _serviceTypeRep.InsertRange(listinfo);
        }
        /// <summary>
        /// 开始服务 
        /// </summary>     
        /// <returns></returns>
        [HttpPost]
        public AssessOrganizationDto BeginOrgAssessService(string gid)
        {
            var model = _orgRep.AsQueryable().Where(m => m.Gid == gid).Select<AssessOrganizationDto>().First();
            if (model == null)
            {
                throw Oops.Bah("未找到该机构信息");
            }
            var listinfo = _serviceInfoRep.AsQueryable().Where(m => m.OrganizationId == gid).OrderBy(m => m.ItemOrderIndex).ToList();

            if (listinfo != null && listinfo.Count > 0)
            {
                model.serviceinfo = listinfo;
            }
            else
            {
                var infoList = new List<cts_OrgAssessServiceInfo>();

                var list = _serviceTypeRep.AsQueryable().OrderBy(m => m.OrderIndex).ToList();
                var savedSql = Guid.NewGuid().ToString();
                foreach (var item in list)
                {
                    var info = new cts_OrgAssessServiceInfo
                    {
                       
                        sys_CreateDate = DateTime.Now,
                        Gid = Guid.NewGuid().ToString(),
                        sys_IsDelete = 0,
                        OrganizationId = model.Gid,
                        OrganizationName = model.Name,
                        SavedSql = savedSql,
                        ItemId = item.Gid,
                        ItemName = item.Name,
                        ItemNoStr = item.NoStr,
                        IsTitle = item.IsTitle,
                        ItemOrderIndex = item.OrderIndex,
                        ItemParentType = item.ParentType,
                        ItemParentType2 = item.ParentType2,
                        ItemParentType3 = item.ParentType3,
                        ItemGrade = item.Grade,
                        ItemAssessDesc = item.AssessDesc

                    };
                    infoList.Add(info);

                }
                _serviceInfoRep.InsertRange(infoList);
                model.serviceinfo = infoList;

            }

            return model;
             
        }

        /// <summary>
        /// 保存单个服务评定
        /// </summary>     
        /// <returns></returns>
        [HttpPost]
        public cts_OrgAssessServiceInfo SaveOrgServiceAssessItem(cts_OrgAssessServiceInfo item)
        {
            item.SaveCount += 1;
            _serviceInfoRep.Update(item);
            return item;
        }



        /// <summary>
        /// 获取服务 
        /// </summary>     
        /// <returns></returns>
        [HttpGet]
        public List<cts_OrgAssessServiceInfo> GetOrgServiceAssess(string id)
        {
            return _serviceInfoRep.GetList(m => m.OrganizationId == id); 
        }


        /// <summary>
        /// 删除服务图片
        /// </summary>     
        /// <returns></returns>
       
        public void DeleteOrgServiceItemImg(string gid)
        {
            _serviceImgRep.AsUpdateable().SetColumns(m=>m.sys_IsDelete==1).Where(m=>m.Gid==gid).ExecuteCommand();
             
        }
        /// <summary>
        /// 获取图片
        /// </summary>     
        /// <returns></returns>
        [HttpGet]
        public List<cts_OrgAssessServiceImg> GetOrgServiceItemImg(string gid)
        {
            return _serviceImgRep.GetList(m => m.OrgItemId == gid);
            
        }
        /// <summary>
        /// 获取未评定的项目 
        /// </summary>     
        /// <returns></returns>
        [HttpGet]
        public List<cts_OrgAssessServiceInfo> GetOrgServiceItemNoAssess(string gid)
        {
            return _serviceInfoRep.GetList(m=>m.OrganizationId== gid&&m.SaveCount<1);
        }

        #endregion

        #region 服务质量基本规范评定
        /// <summary>
        /// 查询服务质量基本规范
        /// </summary>     
        /// <returns></returns>
        [HttpGet]
        public List<cts_OrgAssessServiceBasicType> GetOrgAssessServiceBasicType()
        {

            return _basicTypeRep.AsQueryable().OrderBy(m => m.OrderIndex).ToList(); 
        }
        /// <summary>
        /// 删除服务质量基本规范
        /// </summary>     
        /// <returns></returns>
       
        public void DeleteOrgAssessServiceBasicType(string id)
        {
            _basicTypeRep.AsUpdateable().SetColumns(m => m.sys_IsDelete == 1).Where(m => m.Gid == id).ExecuteCommand();
             
        }
        /// <summary>
        /// 保存服务质量基本规范
        /// </summary>     
        /// <returns></returns>
        [HttpPost]
        public void SaveOrgAssessServiceBasicType(cts_OrgAssessServiceBasicType info)
        {
            //新增
            if (string.IsNullOrEmpty(info.Gid))
            {
                info.Gid = Guid.NewGuid().ToString();
                _basicTypeRep.Insert(info);

            }
            else
            {
                _basicTypeRep.Update(info);
            }
        }

        /// <summary>
        /// 导入服务质量基本规范项目
        /// </summary>     
        /// <returns></returns>
        [HttpPost]
        public void ImportOrgAssessServiceBasicType(List<ImportOrgAssessServiceType> list)
        {
            if (list == null || list.Count == 0)
            {

                throw Oops.Bah("导入数据不能为空");
            }
            List<cts_OrgAssessServiceBasicType> listinfo = new List<cts_OrgAssessServiceBasicType>();
            var index = 0;
            foreach (var item in list)
            {
                index += 1;
                cts_OrgAssessServiceBasicType oa = new cts_OrgAssessServiceBasicType
                {
                    Gid = Guid.NewGuid().ToString(),
                    Name = item.评定项目,
                    ParentType2 = item.评定说明,
                    NoStr = item.序号,
                    OrderIndex = index,
                    AssessDesc = item.操作说明,
                    Grade = item.是否重要,
                    IsTitle = item.是否标题,
                    TitleGrade = item.标题等级,
                    sys_IsDelete = 0
                };
                listinfo.Add(oa);
            }
            _basicTypeRep.Delete(m => true);
            _basicTypeRep.InsertRange(listinfo);
        }
        /// <summary>
        /// 开始服务质量基本规范
        /// </summary>     
        /// <returns></returns> 
        public AssessOrganizationDto BeginOrgAssessServiceBasic(string gid)
        {
            var model = _orgRep.AsQueryable().Where(m => m.Gid == gid).Select<AssessOrganizationDto>().First();
            if (model == null)
            {
                throw Oops.Bah("未找到该机构信息");
            }
            var listinfo = _basicInfoRep.AsQueryable().Where(m => m.OrganizationId == gid).OrderBy(m => m.ItemOrderIndex).ToList();

            if (listinfo != null && listinfo.Count > 0)
            {
                model.servicebasicinfo = listinfo;
            }
            else
            {
                var infoList = new List<cts_OrgAssessServiceBasicInfo>();

                var list = _basicTypeRep.AsQueryable().OrderBy(m => m.OrderIndex).ToList();
                var savedSql = Guid.NewGuid().ToString();
                foreach (var item in list)
                {
                    var info = new cts_OrgAssessServiceBasicInfo
                    {
                        
                        sys_CreateDate = DateTime.Now,
                        Gid = Guid.NewGuid().ToString(),
                        sys_IsDelete = 0,
                        OrganizationId = model.Gid,
                        OrganizationName = model.Name,
                        SavedSql = savedSql,
                        ItemId = item.Gid,
                        ItemName = item.Name,
                        ItemNoStr = item.NoStr,
                        IsTitle = item.IsTitle,
                        ItemOrderIndex = item.OrderIndex,
                        ItemParentType = item.ParentType,
                        ItemParentType2 = item.ParentType2,
                        ItemParentType3 = item.ParentType3,
                        ItemGrade = item.Grade,
                        TitleGrade = item.TitleGrade,
                        ItemAssessDesc = item.AssessDesc

                    };
                    infoList.Add(info);


                }
                _basicInfoRep.InsertRange(infoList);
                model.servicebasicinfo = infoList;

            }

            return model;
        }

        /// <summary>
        /// 保存单个服务质量基本规范
        /// </summary>     
        /// <returns></returns>
        [HttpPost]
        public cts_OrgAssessServiceBasicInfo SaveOrgServiceBasicAssessItem(cts_OrgAssessServiceBasicInfo item)
        {
            item.SaveCount += 1;
            _basicInfoRep.Update(item);
            return item; 
         
        }


        /// <summary>
        /// 获取服务质量基本规范
        /// </summary>     
        /// <returns></returns>
        [HttpGet]
        public List<cts_OrgAssessServiceBasicInfo> GetOrgServiceBasicAssess(string id)
        { 
            return _basicInfoRep.GetList(m => m.OrganizationId == id); 
        }


        /// <summary>
        /// 删除服务图片
        /// </summary>     
        /// <returns></returns>
       
        public void DeleteOrgServiceBasicItemImg(string gid)
        {
            _basicImgRep.AsUpdateable().SetColumns(m => m.sys_IsDelete == 1).Where(m => m.Gid == gid).ExecuteCommand();
 
        }
        /// <summary>
        /// 获取图片
        /// </summary>     
        /// <returns></returns>
        [HttpGet]
        public List<cts_OrgAssessServiceBasicImg> GetOrgServiceBasicItemImg(string gid)
        {
            return _basicImgRep.GetList(m => m.OrgItemId == gid);
        }
        /// <summary>
        /// 获取未评定的项目 
        /// </summary>     
        /// <returns></returns>
        [HttpGet]
        public List<cts_OrgAssessServiceBasicInfo> GetOrgServiceBasicItemNoAssess(string gid)
        {
            return _basicInfoRep.GetList(m => m.OrganizationId == gid && m.SaveCount < 1);
        }

        #endregion


        #region 服务安全规范评定
        /// <summary>
        /// 查询服务质量基本规范
        /// </summary>     
        /// <returns></returns>
        [HttpGet]
        public List<cts_OrgAssessSafeType> GetOrgAssessSafeType()
        {
            return _safeTypeRep.AsQueryable().OrderBy(m => m.OrderIndex).ToList(); 
        }
        /// <summary>
        /// 删除服务质量基本规范
        /// </summary>     
        /// <returns></returns>
       
        public void DeleteOrgAssessSafeType(string id)
        {
            _safeTypeRep.AsUpdateable().SetColumns(m => m.sys_IsDelete == 1).Where(m => m.Gid == id).ExecuteCommand();

            
        }
        /// <summary>
        /// 保存服务质量基本规范
        /// </summary>     
        /// <returns></returns>
        [HttpPost]
        public void SaveOrgAssessSafeType(cts_OrgAssessSafeType info)
        {

            //新增
            if (string.IsNullOrEmpty(info.Gid))
            {
                info.Gid = Guid.NewGuid().ToString();
                _safeTypeRep.Insert(info);

            }
            else
            {
                _safeTypeRep.Update(info);
            }
        }

        /// <summary>
        /// 导入服务质量基本规范项目
        /// </summary>     
        /// <returns></returns>
        [HttpPost]
        public void  ImportOrgAssessSafeType(List<ImportOrgAssessServiceType> list)
        {
            if (list == null || list.Count == 0)
            {

                throw Oops.Bah("导入数据不能为空");
            }
            List<cts_OrgAssessSafeType> listinfo = new List<cts_OrgAssessSafeType>();
            var index = 0;
            foreach (var item in list)
            {
                index += 1;
                cts_OrgAssessSafeType oa = new cts_OrgAssessSafeType
                {
                    Gid = Guid.NewGuid().ToString(),
                    Name = item.评定项目,
                    ParentType2 = item.评定说明,
                    NoStr = item.序号,
                    OrderIndex = index,
                    AssessDesc = item.操作说明,
                    Grade = item.是否重要,
                    IsTitle = item.是否标题,
                    TitleGrade = item.标题等级,
                    sys_IsDelete = 0
                };
                listinfo.Add(oa);
            }
            _safeTypeRep.Delete(m => true);
            _safeTypeRep.InsertRange(listinfo);
        }
        /// <summary>
        /// 开始服务质量基本规范
        /// </summary>     
        /// <returns></returns>
        [HttpPost]
        public AssessOrganizationDto BeginOrgAssessSafe(string gid)
        {
            var model = _orgRep.AsQueryable().Where(m => m.Gid == gid).Select<AssessOrganizationDto>().First();
            if (model == null)
            {
                throw Oops.Bah("未找到该机构信息");
            }
            var listinfo = _safeInfoRep.AsQueryable().Where(m => m.OrganizationId == gid).OrderBy(m => m.ItemOrderIndex).ToList();

            if (listinfo != null && listinfo.Count > 0)
            {
                model.safeinfo = listinfo;
            }
            else
            {
                var infoList = new List<cts_OrgAssessSafeInfo>();

                var list = _safeTypeRep.AsQueryable().OrderBy(m => m.OrderIndex).ToList();
                var savedSql = Guid.NewGuid().ToString();
                foreach (var item in list)
                {
                    var info = new cts_OrgAssessSafeInfo
                    {
                         
                        sys_CreateDate = DateTime.Now,
                        Gid = Guid.NewGuid().ToString(),
                        sys_IsDelete = 0,
                        OrganizationId = model.Gid,
                        OrganizationName = model.Name,
                        SavedSql = savedSql,
                        ItemId = item.Gid,
                        ItemName = item.Name,
                        ItemNoStr = item.NoStr,
                        IsTitle = item.IsTitle,
                        ItemOrderIndex = item.OrderIndex,
                        ItemParentType = item.ParentType,
                        ItemParentType2 = item.ParentType2,
                        ItemParentType3 = item.ParentType3,
                        ItemGrade = item.Grade,
                        TitleGrade = item.TitleGrade,
                        ItemAssessDesc = item.AssessDesc

                    };
                    infoList.Add(info);

                }
                _safeInfoRep.InsertRange(infoList);
                model.safeinfo = infoList;

            }

            return model;
        }

        /// <summary>
        /// 保存单个服务质量基本规范
        /// </summary>     
        /// <returns></returns>
        [HttpPost]
        public cts_OrgAssessSafeInfo SaveOrgSafeAssessItem(cts_OrgAssessSafeInfo item)
        {
            item.SaveCount += 1;
            _safeInfoRep.Update(item);
            return item;
        }


        /// <summary>
        /// 获取服务质量基本规范
        /// </summary>     
        /// <returns></returns>
        [HttpGet]
        public List<cts_OrgAssessSafeInfo> GetOrgSafeAssess(string id)
        {
            return _safeInfoRep.GetList(m => m.OrganizationId == id); 
        }


        /// <summary>
        /// 删除服务图片
        /// </summary>     
        /// <returns></returns>
       
        public void DeleteOrgSafeItemImg(string gid)
        {
            _safeImgRep.AsUpdateable().SetColumns(m => m.sys_IsDelete == 1).Where(m => m.Gid == gid).ExecuteCommand();
             
        }
        /// <summary>
        /// 获取图片
        /// </summary>     
        /// <returns></returns>
        [HttpGet]
        public List<cts_OrgAssessSafeImg> GetOrgSafeItemImg(string gid)
        {
            return _safeImgRep.GetList(m => m.OrgItemId == gid); 
        }
        /// <summary>
        /// 获取未评定的项目 
        /// </summary>     
        /// <returns></returns>
        [HttpGet]
        public List<cts_OrgAssessSafeInfo> GetOrgSafeItemNoAssess(string gid)
        {
            return _safeInfoRep.GetList(m => m.OrganizationId == gid && m.SaveCount < 1);
            
        }

        #endregion







    }
}
